// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper_app/themes/theme.dart';
import 'dart:async';

class ThemeProvider extends ChangeNotifier {
  ThemeData _themeData = lightMode;
  bool _followSystem = false;
  bool _isInitialized = false;
  bool _isDarkMode = false;
  Color _customPrimaryColor = Colors.blueAccent; // 默认自定义颜色
  VoidCallback? _brightnessListener;

  ThemeData get themeData => _themeData;
  bool get isDarkMode => _isDarkMode;
  bool get followSystem => _followSystem;

  ThemeProvider() {
    _initTheme();
  }

  // 初始化主题（异步）
  Future<void> _initTheme() async {
    if (_isInitialized) return;

    final prefs = await SharedPreferences.getInstance();
    _followSystem = prefs.getBool('followSystem') ?? false;
    _customPrimaryColor =
        Color(prefs.getInt('customPrimaryColor') ?? Colors.blueAccent.value);
    _isDarkMode = prefs.getBool('isDark') ?? false;

    if (_followSystem) {
      _themeData = _getSystemTheme();
    } else {
      final isDark = prefs.getBool('isDark') ?? false;
      _themeData = isDark
          ? createThemeData(Brightness.dark, _customPrimaryColor)
          : createThemeData(Brightness.light, _customPrimaryColor);
    }

    _addSystemThemeListener();
    _isInitialized = true;
    notifyListeners();
  }

  // 系统主题监听
  void _addSystemThemeListener() {
    _brightnessListener = () {
      if (_followSystem) {
        _themeData = _getSystemTheme();
        notifyListeners();
      }
    };

    WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
        _brightnessListener;
  }

  // 清理资源
  @override
  void dispose() {
    WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
        null;
    super.dispose();
  }

  // 统一保存配置（异步）
  Future<void> _savePreferences() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isDark', isDarkMode);
    await prefs.setBool('followSystem', _followSystem);
    await prefs.setInt('customPrimaryColor', _customPrimaryColor.value);
  }

  // 切换主题
  void toggleTheme() {
    _followSystem = false;
    _themeData = _isDarkMode
        ? createThemeData(Brightness.light, _customPrimaryColor)
        : createThemeData(Brightness.dark, _customPrimaryColor);
    _isDarkMode = !_isDarkMode;
    _scheduleSavePreferences(); // 异步保存设置
    notifyListeners();
  }

  // 设置浅色主题
  void setLightTheme() {
    _followSystem = false;
    _isDarkMode = false;
    _themeData = createThemeData(Brightness.light, _customPrimaryColor);
    _scheduleSavePreferences(); // 异步保存设置
    notifyListeners();
  }

  // 设置深色主题
  void setDarkTheme() {
    _followSystem = false;
    _isDarkMode = true;
    _themeData = createThemeData(Brightness.dark, _customPrimaryColor);
    _scheduleSavePreferences(); // 异步保存设置
    notifyListeners();
  }

  // 跟随系统主题
  void setFollowSystem() {
    _followSystem = true;
    _themeData = _getSystemTheme();
    _scheduleSavePreferences(); // 异步保存设置
    notifyListeners();
  }

  // 设置自定义主题颜色
  void setCustomTheme(Color primaryColor) {
    if (_followSystem) {
      _customPrimaryColor = primaryColor;
      _themeData = _getSystemTheme();
    } else {
      _customPrimaryColor = primaryColor;
      _themeData = isDarkMode
          ? createThemeData(Brightness.dark, primaryColor)
          : createThemeData(Brightness.light, primaryColor);
    }
    _scheduleSavePreferences(); // 异步保存设置
    notifyListeners();
  }

  // 获取系统主题
  ThemeData _getSystemTheme() {
    final brightness =
        WidgetsBinding.instance.platformDispatcher.platformBrightness;
    return brightness == Brightness.dark
        ? createThemeData(Brightness.dark, _customPrimaryColor)
        : createThemeData(Brightness.light, _customPrimaryColor);
  }

  // 异步保存设置（不会阻塞主线程）
  void _scheduleSavePreferences() {
    Future.microtask(() async {
      await _savePreferences();
    });
  }
}
